package net.coding.bamboo.wex.mq.client.impl;

import com.weihui.basic.lang.common.domain.BaseResult;
import com.weihui.mq.constant.DeliveryMode;
import com.weihui.mq.constant.DestinationType;
import com.weihui.mq.constant.MessageFormat;
import com.weihui.mq.core.MQService;
import com.weihui.mq.request.notify.DefaultNotifyRequest;
import net.coding.bamboo.wex.mq.client.JmsOperationClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * @author : zenghua
 * @version : v0.1 DefaultJmsOperationClient.java
 * @since : 2017/7/17 10:22
 */
@Component("jmsOperationClient")
public class DefaultJmsOperationClient implements JmsOperationClient {

    public static final Logger LOGGER = LoggerFactory.getLogger(DefaultJmsOperationClient.class);

    @Resource(name = "mqService")
    private MQService mqService;

    @Override
    public BaseResult send(String destination, Serializable message) {
        return send(destination, message, DestinationType.QUEUE);
    }

    @Override
    public BaseResult send(String destination, Serializable message, int destinationType) {
        DefaultNotifyRequest<Serializable> notifyRequest = new DefaultNotifyRequest<>();
        try {
            notifyRequest.setDestination(destination);
            notifyRequest.setContent(message);
            notifyRequest.setTransacted(true);
            notifyRequest.setDeliveryMode(DeliveryMode.PERSISTENT);
            notifyRequest.setMessageFormat(message instanceof String ? MessageFormat.TEXT : MessageFormat.OBJECT);
            notifyRequest.setDestinationType(destinationType);

            mqService.sendMessage(notifyRequest);
            return new BaseResult(true);
        } catch (Exception e) {
            LOGGER.error("jms发送消息失败", e);
            return new BaseResult(false);
        }
    }
}
